package com.ruoyi.back.service.impl

import cn.hutool.core.bean.BeanUtil
import com.alibaba.fastjson.JSON
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.kotlin.KtUpdateWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.ruoyi.app.common.Data
import com.ruoyi.app.common.Fail
import com.ruoyi.app.common.Ok
import com.ruoyi.app.common.unitType
import com.ruoyi.back.domain.Member
import com.ruoyi.back.domain.dto.ExperienceMemberDto
import com.ruoyi.back.domain.v2.MemberTask
import com.ruoyi.back.enums.UnitTypeEnum
import com.ruoyi.back.mapper.MemberMapper
import com.ruoyi.back.service.MemberService
import com.ruoyi.back.service.MemberTaskService
import com.ruoyi.common.core.page.TableSupport
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class MemberServiceImpl : ServiceImpl<MemberMapper, Member>(), MemberService {

    @Autowired
    private lateinit var memberTaskService: MemberTaskService

    override fun getNameByMemberId(memberId: Long): String? = getById(memberId)?.name


    override fun saveMember(member: Member): Data<Boolean> = kotlin.run {

        println("开始更新了------------------------------------")
        if (member.setChoose == true) {
            list().forEach {
                updateById(it.apply {
                    setChoose = false
                })
            }
        }

        member.id?.run {
            Ok("更新成功", updateById(member))
        } ?: kotlin.run {
            Ok("保存成功", save(member))
        }
    }

    override fun setDefault(memberId: Long): Data<Boolean> {

        getById(memberId)?.run {
            if (setChoose == true) {
                updateById(this.apply { setChoose = false })
            } else {
                list().forEach {
                    updateById(it.apply {
                        setChoose = false
                    })
                }
                updateById(this.apply { setChoose = true })
            }
        }

        return Ok("设为选中成功", true)
    }

    override fun memberPage(channelType: Int): Page<Member> =
        TableSupport.buildPageRequest().let { pageDomain ->
            page(
                Page(pageDomain.pageNum.toLong(), pageDomain.pageSize.toLong()), KtQueryWrapper(Member::class.java)
                    .eq(Member::channelType, channelType)
                    .orderByAsc(Member::orderNum)
            )
                .let { page: Page<Member> ->
                    page.apply {
                        records = page.records.map {
                            it.apply {
                                periodDesc = "${it.period}${it.periodUnit?.unitType()}"
                                priceDesc = "￥${it.price}"
                                oldPriceDesc = "￥${it.oldPrice}"
                                taskContent = memberTaskService.memberTaskJson(it.id!!)
                            }
                        }
                    }
                }
        }

    override fun memberDay(memberId: Long): Int? =
        getById(memberId)?.run {
            when (periodUnit) {
                UnitTypeEnum.DAY.code -> {
                    if (period != 0) {
                        period
                    } else 100 * 365
                }

                UnitTypeEnum.MONTH.code -> {
                    if (period != 0) {
                        period?.run { this * 30 }
                    } else 100 * 365

                }

                UnitTypeEnum.YEAR.code -> {
                    if (period != 0) {
                        period?.run { this * 365 }
                    } else 100 * 365
                }

                else -> 100 * 365
            }
        }


    override fun removeMember(memberIds: String): Data<Boolean> =
        Ok("批量移除成功", removeByIds(memberIds.split(",")))

    override fun updateExperienceMember(experienceMemberDto: ExperienceMemberDto): Data<Boolean> =
        getById(experienceMemberDto.id)?.run {

            Ok("编辑成功", kotlin.run {
                updateById(this.apply {
                    BeanUtil.copyProperties(experienceMemberDto, this)
                })
                experienceMemberDto.taskContent?.run {
                    memberTaskService.remove(
                        KtUpdateWrapper(MemberTask::class.java)
                            .eq(MemberTask::memberId, experienceMemberDto.id)
                    )
                    JSON.parseArray(this, MemberTask::class.java).run {
                        takeIf { it.isNotEmpty() }
                            ?.run {
                                forEach {
                                    memberTaskService.save(
                                        it.apply {
                                            memberId = experienceMemberDto.id
                                        }
                                    )
                                }
                            }
                    }
                }
                true
            })
        } ?: Fail("不存在当前会员类型")
}